/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.openbookformat.project.newprojectwizard;

import com.smallutil.io.WebUtil;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.htmlparser.util.EncodingChangeException;
import org.htmlparser.util.ParserException;
import org.openbookformat.project.Chapter;
import org.openbookformat.project.HeadingPointer;
import org.openide.util.Exceptions;

/**
 *
 * @author matamh0a
 */
public class NewOBFProjectUtil {
    public static ArrayList<String> getLinks(String contents, String base) {
        ArrayList<String> links = new ArrayList<String>();
        Pattern pattern = Pattern.compile("<a.+href=[\"'](.+?)(\\#.*?)?[\"']");
        Matcher matcher = pattern.matcher(contents);
        String link = null;
        while (matcher.find()) {
            if(!matcher.group().startsWith("http")) {
                //System.out.println(matcher.group(1) + " --> " + base + "\\" + matcher.group(1));
                link = base + "\\" + matcher.group(1);
            } else {
                //System.out.println(matcher.group(1));
                link = matcher.group(1);
            }
            if(!links.contains(link))
                links.add(link);
        }
        return links;
    }
    
    public static Collection<HeadingPointer> getHeadings(String contents, Chapter chpt,
            String pat, int levelGroup, int headingGroup, int baseLevel) {
        ArrayList<HeadingPointer> pointers = new ArrayList<HeadingPointer>();
        Pattern pattern = Pattern.compile(pat);
        Matcher matcher = pattern.matcher(contents);
        int level = baseLevel;
        String heading;
        while (matcher.find()) {
            if(levelGroup > 0) {
                level = Integer.parseInt(matcher.group(levelGroup));
                level = level > baseLevel? level - baseLevel + 1: baseLevel;
            }
            heading = matcher.group(headingGroup);
            pointers.add(new HeadingPointer(chpt, -1 , level, heading));
        }
        return pointers;
    }
    
    public static String getPageCharset(String url) throws IOException, ParserException {
        String[] enc = {"utf-8", "windows-1256"};
        for(int i = 0; i < enc.length; i++) {
            try {
                String contents = WebUtil.getHttp(url, enc[i]);
                Pattern pattern = Pattern.compile("charset\\s*=\\s*['\\\"]?(.+?)['\\\"]*\\s*>");
                Matcher matcher = pattern.matcher(contents);

                if (matcher.find()) {
                    System.out.println(matcher.group(1));
                    return matcher.group(1);
                }
            } catch (EncodingChangeException ECE) {
                System.out.println("Wrong Encoding:" + enc[i]);
            }
        }
        return null;
    }
    
    public static String getPagePattern(String contents) 
            throws IOException, ParserException {
        HashMap<String, Integer> pagePatterns = new HashMap<String, Integer>();
        
        //Pattern pattern = Pattern.compile("\\s*([-{\\Q[\\E\\Q(\\E])?\\s*(\\d+)\\s*([-}\\Q]\\E\\Q)\\E])?\\s*");
        Pattern pattern = Pattern.compile("\n\\s*(\\W)?\\s*(\\d+)\\s*(\\W)?\\s*\n");
        Matcher matcher = pattern.matcher(contents);
        String tmp = null;
        while (matcher.find()) {
            tmp = "\n\\s*" + (matcher.group(1) == null? "": "\\Q" + matcher.group(1) + "\\E") +
                    "\\s*(\\d+)\\s*" 
                    + (matcher.group(3) == null? "": "\\Q" + matcher.group(3) + "\\E") + "\\s*\n";            
            if(pagePatterns.get(tmp) == null) {
                pagePatterns.put(tmp, new Integer(0));
            } else {
                pagePatterns.put(tmp, pagePatterns.get(tmp) + 1);
            }
//            System.out.println(pagePatterns.get(tmp) + " --> " + tmp);
        }
        
        int max = 0;        
        String val = null;
        Iterator<String> it = pagePatterns.keySet().iterator();
        while(it.hasNext()) {
            val = it.next();
            if(pagePatterns.get(val) > max) {
                max = pagePatterns.get(val);
                tmp = val;
            }
        }
        
        return tmp;
    }
    
    public static String html2Text(String contents) {
        return StringEscapeUtils.unescapeHtml(contents.replaceAll("<.*?>", "").
                replaceAll("\n{3,}", "\n\n"));
    }
    
    public static int[] getFirstnLastPage(String url, String encoding, 
            String pat, boolean useGroup, int group) {
        int[] r = {-1, -1};
        Pattern pattern = Pattern.compile(pat);
        Matcher matcher = null;
        try {
            matcher = pattern.matcher(NewOBFProjectUtil.html2Text(
            WebUtil.getHttp(url, encoding)));
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        } catch (ParserException ex) {
            Exceptions.printStackTrace(ex);
        }
        if (matcher.find()) {
            if (useGroup) {
                r[0] = Integer.parseInt(matcher.group(group));
            } else {
                r[0] = Integer.parseInt(matcher.group());
            }
            r[1] = r[0];
        }
        while (matcher.find()) {
            if (useGroup) {
                r[1] = Integer.parseInt(matcher.group(group));
            } else {
                r[1] = Integer.parseInt(matcher.group());
            }
        }
        return r;
    }
    
}
